import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Button, DatePicker, Table, Input, Icon, Tooltip as AntdTooltip, message, Skeleton  } from 'antd';
import { Coord , Chart, Geom, Axis, Legend, Tooltip } from 'bizcharts';
import { ChartCard, Pie} from '@/components/Charts';
import { getAccess } from '@/utils/accessFunctions';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DetailModel from './DetailModel';

import styles from './warnList.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

/* eslint react/no-multi-comp:0 */
@connect(({ loading, warning, menuTree }) => ({
  loading: loading.models.warning,
  warning,
  menuTree: menuTree.menuData,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    access: {},
    modalVisible: false,
    updateModalVisible: false,
    detailModalVisible: false,
    selectedRows: [],
    formValues: {
      page: '1',
      pageSize: 5,
      startTime: '',
      endTime: '',
      plateNoList: [],
    }, //obd列表查询条件
    detailFormValues: {},
    plateNoValue:"",
    lineChart: [], 
    lineArry:[],
    coodChart:[],
    salesPieData:[],
    plateNo:""
  };
  
  columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      key: 'index',
    },
    {
      title: '车牌号',
      dataIndex: 'plateNo',
    },
    {
      title: '急加速',
      dataIndex: 'accelerate',
    },
    {
      title: '急减速',
      dataIndex: 'decelerate',
    },
    {
      title: '急转弯',
      dataIndex: 'turn',
    },
    {
      title: '疲劳驾驶',
      dataIndex: 'fatigue',
    },
    {
      title: '分神',
      dataIndex: 'distract',
    },
    {
      title: '得分',
      dataIndex: 'drivePoint',
    },
    // {
    //   title: '状态',
    //   dataIndex: 'online',
    //   render(val) {
    //     return <Badge status={val ? 'success' : 'error'} text={val ? '在线' : '不在线'} />;
    //   }
    // },
    {
      title: '创建时间',
      dataIndex: 'gmt_create',
      render(val){
        return val.split(" ")[0]
      }
    },
  ];

  componentDidMount() {
    const {
      dispatch,
      location: { pathname },
      menuTree,
    } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'warning/fetchQueryDriverBehavior',
      payload: formValues
    });

    const access = getAccess(pathname, menuTree);
    this.setState({
      access: access.childMap || {},
    });
  }
  // 分页change
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const params = {
      ...formValues,
      page: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.setState({
      formValues: {
        ...params,
      },
    });
    dispatch({
      type: 'warning/fetchQueryDriverBehavior',
      payload: params,
      callback:(res)=>{
        if (res.code !== "000000") { message.warning(res.msg); return }
        this.formatPieData(res.list[0])
      }
    });
  };
  // 查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = null;
      var rangeValue = fieldsValue['chooseTime'];
      if (rangeValue !== undefined && rangeValue.length !== 0) {
        rangeValue = [
          rangeValue[0].format('YYYY-MM-DD') + " 00:00:00",
          rangeValue[1].format('YYYY-MM-DD') + " 23:59:59",
        ];
      } else {
        rangeValue = ['', ''];
      }
      values = {
        ...this.state.formValues,
        startTime: rangeValue[0],
        endTime: rangeValue[1],
        page: 1,
      };

      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'warning/fetchQueryDriverBehavior',
        payload: values,
        callback:(res)=>{
          if(res.code !== "000000"){message.warning(res.msg);return}
          if(res.list.length == 0){message.warning("暂无数据！");return}
          const data = {
            dateList: res.dateList || [],
            totalPointList: res.totalPointList
          }
          this.formatPieData(res.list[0])
          this.formatCharts(data)
        }
      });
    });
  };
  handleRowClick=(record)=>{
    const salesPieData = [
      {
        x: '急加速',
        y: record.accelerate,
      },
      {
        x: '急减速',
        y: record.decelerate,
      },
      {
        x: '急转弯',
        y: record.turn,
      },
      {
        x: '疲劳驾驶',
        y: record.fatigue,
      },
      {
        x: '分神',
        y: record.distract,
      },
    ];
    const plateNo = record.plateNo
    this.setState({
      salesPieData,
      plateNo
    })
  }
  // 饼状图数据源
  formatPieData = (record)=>{
    this.handleRowClick(record)
  }
  // 序列化图形格式
  formatCharts = (data)=>{
    // 折线图
    const lineChart = data.dateList.map( item => {
      const obj = {}
      item.map((list,index) =>{
        obj[list.plateNo] = list.drivePoint,
        obj.gmt_create = list.gmt_create.split(" ")[0]
      })
      return obj 
    })
    const lineArry = data.totalPointList.map(item => item.plateNo)
    // 柱状图 totalPointList
    const coodChart = data.totalPointList
    this.setState({
      lineChart,
      lineArry,
      coodChart
    })
  }
  // 查看设备详情
  handleDetailModalVisible = (flag, record) => {
    this.setState({
      detailModalVisible: !!flag,
      detailFormValues: record || {},
    });
  };
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { access } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col xl={10} lg={8} md={11} sm={12} xs={24}>
            <FormItem label="选择时间">
              {getFieldDecorator('chooseTime', {})(
                <RangePicker
                  allowClear
                  format="YYYY-MM-DD"
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col xl={8} lg={6} md={7} sm={12}  xs={24}>
            <FormItem label="车牌号">
              {getFieldDecorator('plateNoList', {
                initialValue:this.state.plateNoValue
              })(
                <Input autoComplete="off" onClick={this.handleDetailModalVisible}  />
              )}
              </FormItem>
          </Col>
          {/* <Col sm={1}>
            <AntdTooltip title="What do you want others to call you?">
              <Icon type="question-circle-o" />
            </AntdTooltip>
          </Col> */}
          <Col xl={4} lg={4} md={4} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  // 车辆勾选回调
  handleDetail=(fields)=>{
    const plateNos = fields.selectedRowKeys
    const data = {
      ...this.state.formValues,
      plateNoList: plateNos
    }
    this.setState({
      formValues:data,
      plateNoValue: `已选：${plateNos.length}个`
    })
    this.handleDetailModalVisible()
  }
  render() {
    const {
      loading,
      warning: { driverBehaviorLists },
    } = this.props;
    const { detailModalVisible, detailFormValues, lineChart,access, lineArry, coodChart, salesPieData, plateNo} = this.state;
    // console.log(access)

    // 查看
    const detailMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
      handleDetail: this.handleDetail,
    };
    // 折线图
    const dsLine = new DataSet();
    const dvLine = dsLine.createView().source(lineChart);
    dvLine.transform({
      type: "fold",
      fields: lineArry,
      // 展开字段集
      key: "date",
      // key字段
      value: "score" // value字段
    });
    const colsLine = {
      gmt_create: {
        range: [0, 1]
      }
    };
    // 柱状图
    const dsCood = new DataSet();
    const dvCood = dsCood.createView().source(coodChart);
    dvCood.source(coodChart).transform({
      type: "sort",
      callback(a, b) {
        // 排序依据，和原生js的排序callback一致
        return a.totalPoint - b.totalPoint > 0;
      }
    });
    return (
      <PageHeaderWrapper title="报警列表">        
        {detailModalVisible ? (
          <DetailModel
            {...detailMethods}
            detailModalVisible={detailModalVisible}
            values={detailFormValues}
            dispatch={this.props.dispatch}
          />
        ) : null} 
        <Row gutter={24}>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Card bordered={false}>
              <div style={{height:"340px"}}>
                <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                <div className={styles.tableList}>
                  {driverBehaviorLists && Object.keys(driverBehaviorLists).length ? (
                    <Table
                      loading={loading}
                      dataSource={driverBehaviorLists.list}
                      columns={this.columns}
                      pagination={driverBehaviorLists.pagination}
                      onChange={this.handleStandardTableChange}
                      rowKey={record => record.id}
                      size="small"
                      onRow={(record, index) => {
                        return {
                          onClick: () => {
                            this.handleRowClick(record, index);
                          },
                        };
                      }}
                    />
                  ) : null}
                </div>            
              </div>
              </Card>
          </Col>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <ChartCard
              title={plateNo}
              action={
                <AntdTooltip title={plateNo}>
                  <Icon type="exclamation-circle-o" />
                </AntdTooltip>
              }
              contentHeight={300}
            >
              {salesPieData && Object.keys(salesPieData).length?
                <Pie
                  hasLegend
                  title="违规次数"
                  subTitle="违规总次数"
                  total={() => (
                    <span
                      dangerouslySetInnerHTML={{
                        __html: (salesPieData.reduce((pre, now) => now.y + pre, 0))
                      }}
                    />
                  )}
                  data={salesPieData}
                  valueFormat={val => <span dangerouslySetInnerHTML={{ __html: val }} />}
                  height={294}
                />
                : <Skeleton active paragraph={{ rows: 4 }} />
              }
            </ChartCard>
          </Col>
        </Row>
        <div style={{height:"15px"}}></div>
        <Row gutter={24}>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <ChartCard
              title="分段评级信息"
              action={
                <AntdTooltip title="车辆分段评级信息">
                  <Icon type="exclamation-circle-o" />
                </AntdTooltip>
              }
              contentHeight={300}
            >
                {
                  lineChart && Object.keys(lineChart).length?
                    <Chart height={300} width={300} data={dvLine} scale={colsLine} forceFit>
                      <Legend />
                      <Axis name="gmt_create" />
                      <Axis
                        name="score"
                        label={{
                          formatter: val => `${val}`
                        }}
                      />
                      <Tooltip
                        crosshairs={{
                          type: "y"
                        }}
                      />
                      <Geom
                        type="line"
                        position="gmt_create*score"
                        size={2}
                        color={"date"}
                        shape={"smooth"}
                      />
                      <Geom
                        type="point"
                        position="gmt_create*score"
                        size={4}
                        shape={"circle"}
                        color={"date"}
                        style={{
                          stroke: "#fff",
                          lineWidth: 1
                        }}
                      />
                    </Chart>
                  : <Skeleton active paragraph={{ rows: 4 }} />

                }
            </ChartCard>
          </Col>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <ChartCard
              title="车辆评分排名"
              action={
                <AntdTooltip title="车辆评分排名">
                  <Icon type="exclamation-circle-o" />
                </AntdTooltip>
              }
              contentHeight={300}
            >
            {
                coodChart && Object.keys(coodChart).length ?
                  <Chart height={300} data={dvCood} forceFit>
                    <Coord transpose />
                    <Axis
                      name="plateNo"
                      label={{
                        offset: 12
                      }}
                    />
                    <Axis name="population" />
                    <Tooltip />
                    <Geom type="interval" position="plateNo*totalPoint" />
                  </Chart>
                  : <Skeleton active paragraph={{ rows: 4 }}/>
            }              
            </ChartCard>
          </Col>
        </Row>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
